package com.tuanzi.loan.web.bean.system;

import com.tuanzi.loan.business.entity.CurrentUser;
import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.service.system.DictionaryService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.system.DictionarySearchRequest;
import com.tuanzi.loan.vo.response.system.DictionarySearchResponse;
import com.tuanzi.loan.web.configuration.JSFListingSessionBean;
import com.tuanzi.loan.web.lazy.system.DictionaryLazyDataModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.faces.bean.ViewScoped;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Ray 2017/09/21
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class DictionaryListBean extends JSFListingSessionBean<DictionarySearchRequest, DictionarySearchResponse> {

	private static final long serialVersionUID = -2152778554108785342L;
	@Autowired
	private DictionaryService dictionaryService;

	public void onReset() {
		initLazyDataModel();
	}

	public String onAdd() {
		return redirect("/views/system/dictionary/dictionary-info.xhtml");
	}

	public String onEdit(String id) {
		return redirect("/views/system/dictionary/dictionary-info.xhtml?id=" + id);
	}

	public void onBatchDisable() {
		dictionaryService.disable(getSelectedDictionaries());
		addSuccessfullyMessage();
	}

	public void onBatchEnable() {
		dictionaryService.enable(getSelectedDictionaries());
		addSuccessfullyMessage();
	}

	public void onDisable(String id) {
		CurrentUser.get();
		dictionaryService.disable(dictionaryService.findOne(id));
		addSuccessfullyMessage();
	}

	public void onEnable(String id) {
		dictionaryService.enable(dictionaryService.findOne(id));
		addSuccessfullyMessage();
	}

	public void onDelete(String id){
		dictionaryService.delete(dictionaryService.findOne(id));
		addSuccessfullyMessage();
	}

	public void onBatchDelete(){
		dictionaryService.delete(getSelectedDictionaries());
		addSuccessfullyMessage();
	}

	public void onRefreshCache() {
		dictionaryService.onRefreshCache();
		addSuccessfullyMessage();
	}

	private List<Dictionary> getSelectedDictionaries() {
		return dictionaryService.findAll(selectedRecords.parallelStream().map(DictionarySearchResponse::getId).map(x -> x.toString()).collect(Collectors.toList()));
	}

	@Override
	protected String page() {
		return "/views/system/dictionary/dictionary-list.xhtml";
	}

	@Override
	protected void initLazyDataModel() {
		$ = new DictionarySearchRequest();
		lazyDataModel = new DictionaryLazyDataModel($, session, dictionaryService);
	}
}
